<template>
  <view class="home-container">
    <!-- 诗意时光小径首页 -->
    <scroll-view
      class="main-scroll"
      scroll-y
      :refresher-enabled="true"
      :refresher-triggered="triggered"
      @refresherrefresh="onRefresh"
      @scrolltolower="loadMore"
    >
      <!-- 诗意时光小径容器 -->
      <view class="poetic-path-wrapper">
        <!-- 天空背景 -->
        <view class="sky-background">
          <!-- 太阳 -->
          <view class="sun"></view>
          <!-- 云朵 -->
          <view class="cloud cloud-1"></view>
          <view class="cloud cloud-2"></view>
          <view class="cloud cloud-3"></view>
        </view>

        <!-- 远山 -->
        <view class="distant-mountains"></view>

        <!-- 连续蜿蜒小径 -->
        <view class="continuous-winding-path">
          <!-- 远景小径 -->
          <view class="path-layer far-path-layer">
            <view
              class="path-segment far-path"
              v-for="(segment, index) in pathSegments"
              :key="`far-${index}`"
              :style="getPathSegmentStyle(segment, 'far', index)"
            ></view>
          </view>

          <!-- 中景小径 -->
          <view class="path-layer middle-path-layer">
            <view
              class="path-segment middle-path"
              v-for="(segment, index) in pathSegments"
              :key="`middle-${index}`"
              :style="getPathSegmentStyle(segment, 'middle', index)"
            ></view>
          </view>

          <!-- 近景小径 -->
          <view class="path-layer near-path-layer">
            <view
              class="path-segment near-path"
              v-for="(segment, index) in pathSegments"
              :key="`near-${index}`"
              :style="getPathSegmentStyle(segment, 'near', index)"
            ></view>
          </view>
        </view>

        <!-- 时光记忆片段 -->
        <view class="memory-fragments">
          <view
            v-for="(item, index) in allItems"
            :key="index"
            class="fragment-item"
            :class="{ 'right-side': index % 2 === 1 }"
          >
            <!-- 记忆光晕 -->
            <view
              class="memory-halo"
              :style="{ backgroundColor: `rgba(${getThemeRGB()}, 0.4)` }"
            ></view>

            <!-- 记忆胶囊 -->
            <view class="memory-capsule" @click="playVideo(item)">
              <view class="capsule-shadow"></view>
              <view
                class="capsule-content"
                :style="{
                  transform: `rotateX(${item.rotationX || 0}deg) rotateY(${
                    item.rotationY || 0
                  }deg)`,
                }"
              >
                <!-- 封面图片占满整个卡片 -->
                <image
                  :src="item.cover || '/static/images/video1.jpg'"
                  mode="aspectFill"
                  class="capsule-image"
                  @error="onImageError"
                />

                <!-- 毛玻璃效果信息层 -->
                <view class="glass-info-overlay">
                  <view class="glass-content">
                    <text class="author-text">{{ item.title }}</text>
                    <text class="author-text">{{ item.author }}</text>
                    <text class="play-count-text"
                      >{{ item.playCount }}次观看</text
                    >
                  </view>
                </view>
              </view>
            </view>

            <!-- 时间标签 -->
            <view class="time-tag">
              <view class="tag-content" :style="currentGradient">
                {{
                  formatTimestamp(
                    item.timestamp ||
                      new Date(Date.now() - index * 24 * 60 * 60 * 1000)
                  )
                }}
              </view>
            </view>
          </view>
        </view>

        <!-- 远方光芒 -->
        <view class="distant-glow"></view>
      </view>

      <!-- 加载状态 -->
      <view class="loading-status">
        <text
          v-if="loading"
          class="loading-text"
          :style="{ color: currentTheme.primary }"
          >时光流转中...</text
        >
        <text
          v-if="noMore"
          class="no-more-text"
          :style="{ color: currentTheme.primary }"
          >已至时光尽头</text
        >
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { getCurrentTheme } from "@/utils/theme";

// 视频数据（单列）
const allItems = ref<any[]>([]);

// 分页状态
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const noMore = ref(false);
const triggered = ref(false);

// 获取当前主题
const currentTheme = computed(() => getCurrentTheme());

// 计算当前主题的渐变样式
const currentGradient = computed(() => {
  return `background: linear-gradient(135deg, ${currentTheme.value.start} 0%, ${currentTheme.value.end} 100%);`;
});

// 根据主题色获取RGB值
const getThemeRGB = () => {
  const theme = getCurrentTheme();
  // 简单转换十六进制颜色到RGB
  const hexToRgb = (hex: string) => {
    const r = parseInt(hex.slice(1, 3), 16);
    const g = parseInt(hex.slice(3, 5), 16);
    const b = parseInt(hex.slice(5, 7), 16);
    return `${r}, ${g}, ${b}`;
  };

  // 根据主题色返回对应的RGB值
  if (theme.start === "#8e44ad") return "142, 68, 173"; // 紫色
  if (theme.start === "#c0392b") return "192, 57, 43"; // 红色
  if (theme.start === "#2980b9") return "41, 128, 185"; // 蓝色
  if (theme.start === "#16a085") return "22, 160, 133"; // 绿色
  if (theme.start === "#d35400") return "211, 84, 0"; // 金色
  if (theme.start === "#34495e") return "52, 73, 94"; // 墨色
  return "139, 195, 74"; // 默认绿色
};

// 生成蜿蜒路径点
const generateWindingPath = () => {
  const segments = [];
  let currentLeft = 50;

  for (let i = 0; i <= 100; i += 2) {
    // 创建自然的蜿蜒效果
    const wave1 = Math.sin(i * 0.2) * 15;
    const wave2 = Math.sin(i * 0.05) * 10;
    currentLeft = 50 + wave1 + wave2;

    // 限制在屏幕范围内
    currentLeft = Math.max(20, Math.min(80, currentLeft));

    segments.push({
      top: i,
      left: currentLeft,
      width: 80 + Math.sin(i * 0.1) * 20, // 宽度也随着变化
    });
  }

  return segments;
};

// 路径段数据
const pathSegments = generateWindingPath();

// 格式化时间戳
const formatTimestamp = (timestamp: Date) => {
  const date = new Date(timestamp);
  const month = date.getMonth() + 1;
  const day = date.getDate();
  return `${month}月${day}日`;
};

// 生成随机旋转角度 (X轴: -25到25度, Y轴: -45到45度)
const generateRandomRotationX = () => {
  return (Math.random() - 0.5) * 50; // -25 到 25 度
};

const generateRandomRotationY = () => {
  return (Math.random() - 0.5) * 90; // -45 到 45 度
};

// 获取路径段样式
const getPathSegmentStyle = (segment: any, layer: string, index: number) => {
  let width = segment.width;
  let height = 20;
  let opacity = 0.6;

  // 根据层级调整样式
  switch (layer) {
    case "far":
      width *= 0.6;
      height = 12;
      opacity = 0.4;
      break;
    case "middle":
      width *= 0.8;
      height = 16;
      opacity = 0.6;
      break;
    case "near":
      height = 20;
      opacity = 0.8;
      break;
  }

  // 根据当前主题调整小径颜色
  let bgColor = "";
  switch (layer) {
    case "far":
      bgColor = `rgba(${getThemeRGB()}, 0.4)`;
      break;
    case "middle":
      bgColor = `rgba(${getThemeRGB()}, 0.6)`;
      break;
    case "near":
      bgColor = `rgba(${getThemeRGB()}, 0.8)`;
      break;
  }

  return {
    top: `${segment.top}%`,
    left: `${segment.left}%`,
    width: `${width}rpx`,
    height: `${height}rpx`,
    opacity: opacity,
    backgroundColor: bgColor,
    transform: `translateX(-50%) ${
      layer === "far"
        ? "translateZ(-200px)"
        : layer === "middle"
        ? "translateZ(-100px)"
        : "translateZ(0)"
    }`,
  };
};

// 图片加载错误处理
const onImageError = (e: any) => {
  console.log("图片加载失败:", e);
};

// 模拟API请求
const fetchVideos = async (page: number) => {
  return new Promise<any[]>((resolve) => {
    setTimeout(() => {
      resolve(
        Array.from({ length: pageSize.value }, (_, i) => ({
          id: page * 100 + i,
          title: `时光记忆 ${page * 100 + i}`,
          desc: "岁月长河中的珍贵片段",
          cover: `/static/images/video/1.jpg`,
          url: "https://example.com/video.mp4",
          author: "时光收藏家",
          playCount: Math.floor(Math.random() * 1000),
          duration: `${Math.floor(Math.random() * 10) + 5}:${
            Math.random() > 0.5 ? "30" : "00"
          }`,
          timestamp: new Date(
            Date.now() -
              (page - 1) * pageSize.value * 24 * 60 * 60 * 1000 -
              i * 24 * 60 * 60 * 1000
          ),
          rotationX: generateRandomRotationX(),
          rotationY: generateRandomRotationY(),
        }))
      );
    }, 200);
  });
};

// 初始化加载
onMounted(() => {
  loadData();
});

// 加载数据
const loadData = async () => {
  loading.value = true;
  const data = await fetchVideos(currentPage.value);

  if (currentPage.value === 1) {
    // 刷新时清空数据
    allItems.value = [];
  }

  // 添加新数据
  allItems.value.push(...data);

  noMore.value = data.length < pageSize.value;
  loading.value = false;
  triggered.value = false;
};

// 下拉刷新
const onRefresh = async () => {
  triggered.value = true;
  currentPage.value = 1;
  await loadData();
};

// 上拉加载
const loadMore = async () => {
  if (loading.value || noMore.value) return;
  currentPage.value++;
  await loadData();
};

// 跳转视频详情
const playVideo = (video: any) => {
  uni.navigateTo({
    url: `/pages/video/detail?id=${video.id}`,
  });
};
</script>

<style scoped lang="scss">
.home-container {
  width: 100%;
  height: 100vh;
  /* 背景稍微暗一点 */
  background: linear-gradient(160deg, #88c6c0 0%, #dab0c0 100%);
  overflow: hidden;
}

.main-scroll {
  height: 100vh;
}

/* 诗意时光小径容器 */
.poetic-path-wrapper {
  position: relative;
  min-height: 100%;
  padding: 40rpx 20rpx;
  overflow: hidden;
}

/* 天空背景 */
.sky-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 40%;
  /* 背景稍微暗一点 */
  background: linear-gradient(180deg, #67aeca 0%, #94c0e0 100%);
  z-index: 1;
  overflow: hidden;
}

/* 太阳 */
.sun {
  position: absolute;
  top: 15%;
  right: 15%;
  width: 60rpx;
  height: 60rpx;
  background: radial-gradient(
    circle,
    #ffeb3b 0%,
    #ffc107 70%,
    transparent 100%
  );
  border-radius: 50%;
  box-shadow: 0 0 30rpx 15rpx rgba(255, 235, 59, 0.4);
  animation: sunGlow 4s infinite alternate;
}

@keyframes sunGlow {
  0% {
    box-shadow: 0 0 30rpx 15rpx rgba(255, 235, 59, 0.4);
  }
  100% {
    box-shadow: 0 0 40rpx 20rpx rgba(255, 235, 59, 0.6);
  }
}

/* 云朵 */
.cloud {
  position: absolute;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  filter: blur(2rpx);

  &::before,
  &::after {
    content: "";
    position: absolute;
    background: inherit;
    border-radius: 50%;
  }
}

.cloud-1 {
  top: 10%;
  left: 10%;
  width: 80rpx;
  height: 30rpx;

  &::before {
    width: 40rpx;
    height: 40rpx;
    top: -15rpx;
    left: 10rpx;
  }

  &::after {
    width: 50rpx;
    height: 50rpx;
    top: -20rpx;
    right: 10rpx;
  }

  animation: cloudFloat 20s infinite linear;
}

.cloud-2 {
  top: 20%;
  right: 20%;
  width: 100rpx;
  height: 35rpx;

  &::before {
    width: 50rpx;
    height: 50rpx;
    top: -20rpx;
    left: 15rpx;
  }

  &::after {
    width: 60rpx;
    height: 60rpx;
    top: -25rpx;
    right: 15rpx;
  }

  animation: cloudFloat 25s infinite linear reverse;
}

.cloud-3 {
  top: 5%;
  right: 40%;
  width: 60rpx;
  height: 25rpx;

  &::before {
    width: 30rpx;
    height: 30rpx;
    top: -10rpx;
    left: 5rpx;
  }

  &::after {
    width: 35rpx;
    height: 35rpx;
    top: -12rpx;
    right: 5rpx;
  }

  animation: cloudFloat 18s infinite linear;
}

@keyframes cloudFloat {
  0% {
    transform: translateX(-50rpx);
  }
  100% {
    transform: translateX(50rpx);
  }
}

/* 远山 */
.distant-mountains {
  position: absolute;
  bottom: 35%;
  left: 0;
  width: 100%;
  height: 25%;
  background: linear-gradient(
      to top,
      rgba(160, 128, 74, 0.2) 0%,
      transparent 100%
    ),
    linear-gradient(to top, rgba(139, 115, 85, 0.3) 0%, transparent 100%),
    linear-gradient(to top, rgba(93, 109, 126, 0.2) 0%, transparent 100%);
  background-size: 40% 100%, 30% 80%, 35% 60%;
  background-position: 10% 100%, 50% 100%, 80% 100%;
  background-repeat: no-repeat;
  z-index: 2;
}

/* 连续蜿蜒小径 */
.continuous-winding-path {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 3;
  perspective: 1000px;
}

.path-layer {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  transform-style: preserve-3d;
}

/* 远景小径层 */
.far-path-layer {
  z-index: 1;
}

/* 中景小径层 */
.middle-path-layer {
  z-index: 2;
}

/* 近景小径层 */
.near-path-layer {
  z-index: 3;
}

.path-segment {
  position: absolute;
  border-radius: 10rpx;
  transform-style: preserve-3d;
  transform-origin: center;
}

/* 添加小径纹理 */
.path-segment::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: repeating-linear-gradient(
    90deg,
    transparent,
    transparent 10rpx,
    rgba(255, 255, 255, 0.1) 10rpx,
    rgba(255, 255, 255, 0.1) 20rpx
  );
  border-radius: inherit;
}

/* 时光记忆片段 */
.memory-fragments {
  position: relative;
  z-index: 4;
  padding: 120rpx 0;
}

.fragment-item {
  position: relative;
  margin-bottom: 140rpx;
  display: flex;
  align-items: center;

  &:nth-child(odd) {
    flex-direction: row;
    padding-left: 15%;
    padding-right: 45%;

    .time-tag {
      left: 5%;
    }
  }

  &:nth-child(even) {
    flex-direction: row-reverse;
    padding-right: 15%;
    padding-left: 45%;

    .time-tag {
      right: 5%;
    }
  }

  /* 创建蜿蜒效果 */
  &:nth-child(4n + 1) {
    margin-top: 50rpx;
  }
  &:nth-child(4n + 2) {
    margin-top: -40rpx;
  }
  &:nth-child(4n + 3) {
    margin-top: 60rpx;
  }
  &:nth-child(4n + 4) {
    margin-top: -50rpx;
  }
}

/* 记忆光晕 */
.memory-halo {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 280rpx;
  height: 280rpx;
  border-radius: 50%;
  z-index: -1;
  animation: pulse 3s infinite alternate;
}

@keyframes pulse {
  0% {
    opacity: 0.3;
    transform: translate(-50%, -50%) scale(1);
  }
  100% {
    opacity: 0.6;
    transform: translate(-50%, -50%) scale(1.2);
  }
}

/* 记忆胶囊 */
.memory-capsule {
  flex: 1;
  max-width: 80%;
  position: relative;
  cursor: pointer;
  transition: transform 0.3s ease;
  transform-style: preserve-3d;
  perspective: 1000px;

  &:active {
    transform: scale(0.95);
  }
}

.capsule-shadow {
  position: absolute;
  bottom: -30rpx;
  left: 10%;
  width: 80%;
  height: 35rpx;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 50%;
  filter: blur(15rpx);
  z-index: -1;
}

/* 提亮视频卡片 */
.capsule-content {
  position: relative;
  background: linear-gradient(135deg, #ffffff 0%, #ffffff 100%);
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 30rpx 60rpx rgba(0, 0, 0, 0.15),
    0 15rpx 25rpx rgba(0, 0, 0, 0.1);
  border: 1rpx solid rgba(255, 255, 255, 0.8);
  transform-style: preserve-3d;
  transition: transform 0.5s ease;
  transform: rotateX(0deg) rotateY(0deg);
  width: 360rpx;
  height: 640rpx;
}

/* 封面图片占满整个卡片 */
.capsule-image {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: cover;
  background-color: #f0f0f0;
}

/* 毛玻璃效果信息层 - 背景稍微暗一点 */
.glass-info-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: flex-end;
  padding: 30rpx;
  box-sizing: border-box;
  background: linear-gradient(
    to top,
    rgba(0, 0, 0, 0.8) 0%,
    rgba(0, 0, 0, 0.4) 50%,
    transparent 100%
  );
}

.glass-content {
  width: 100%;
  /* 增强毛玻璃效果 */
  backdrop-filter: blur(15rpx);
  -webkit-backdrop-filter: blur(15rpx);
  /* 调整背景色使其更好地融合 */
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 16rpx;
  padding: 20rpx;
  box-sizing: border-box;
}

.author-text,
.play-count-text {
  display: block;
  /* 字体小一点 */
  font-size: 18rpx;
  /* 颜色调整使其更好地融合 */
  color: rgba(255, 255, 255, 0.7);
  /* 减少文字阴影让其不那么突出 */
  text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.3);
  /* 增加字间距提高可读性 */
  letter-spacing: 1rpx;
}

.author-text {
  font-weight: 500;
  margin-bottom: 8rpx;
}

.play-count-text {
  opacity: 0.8;
}

/* 时间标签 */
.time-tag {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  z-index: 5;
}

.tag-content {
  color: white;
  padding: 15rpx 28rpx;
  border-radius: 28rpx;
  font-size: 28rpx;
  font-weight: 500;
  box-shadow: 0 10rpx 20rpx rgba(139, 195, 74, 0.4),
    0 5rpx 10rpx rgba(139, 195, 74, 0.2);
  white-space: nowrap;
  position: relative;

  &::before {
    content: "";
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    width: 16rpx;
    height: 16rpx;
    border-radius: 50%;
  }
}

.fragment-item:nth-child(odd) .tag-content::before {
  right: -25rpx;
  background: linear-gradient(135deg, #8bc34a 0%, #4caf50 100%);
}

.fragment-item:nth-child(even) .tag-content::before {
  left: -25rpx;
  background: linear-gradient(135deg, #8bc34a 0%, #4caf50 100%);
}

/* 远方光芒 */
.distant-glow {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 150rpx;
  background: radial-gradient(
    circle at center bottom,
    rgba(255, 255, 255, 0.5) 0%,
    transparent 70%
  );
  z-index: 2;
  pointer-events: none;
}

/* 加载状态 */
.loading-status {
  padding: 40rpx;
  text-align: center;
  position: relative;
  z-index: 5;

  .loading-text,
  .no-more-text {
    font-size: 26rpx;
    font-weight: 500;
  }
}
</style>
